<?php

	return;
	
	// define('IN_NWIDC',1);
	// define('APP_ID','shop');
	// define('BASE_PATH',str_replace('\\','/',dirname(__FILE__) . '/shop'));
	// if (!@include(dirname((__FILE__)).'/global.php')) exit('global.php isn\'t exists!');
	// if (!@include(BASE_PATH.'/control/control.php')) exit('control.php isn\'t exists!');
	// if (!@include(BASE_CORE_PATH.'/nwidc.php')) exit('nwidc.php isn\'t exists!');
	// define('APP_SITE_URL',SHOP_SITE_URL);
	// define('TPL_NAME',TPL_SHOP_NAME);
	// define('SHOP_RESOURCE_SITE_URL',SHOP_SITE_URL.DS.'resource');
	// define('SHOP_TEMPLATES_URL',SHOP_SITE_URL.'/templates/'.TPL_NAME);
	// define('BASE_TPL_PATH',BASE_PATH.'/templates/'.TPL_NAME);

	require_once(dirname(BASE_PATH) . '/custom/hangzhou/hangzhou_define.php');

	set_time_limit(0);

	$param = array(
		'ip' => '127.0.0.1',
		'v' => '1.0',
		'appKey' => 'SPWLA',
		'company_code' => 'SPWL',
		'sessionKey' => '2015SPWLAV1'
	);

	$send_goods_url = 'http://60.191.39.196:8001/ecm/interface/rest/SPWLInterface/sendCommodity';
	$porder_url = '';

	mysql_query("set names utf8");

	if(isset($_GET['interface'])){
		$interface = trim($_GET['interface']);

		//6.	回传实际入库数量
		if($interface == 'sendRealStockInAmount'){
			$json = json_decode(base64_decode($_POST['JSON_OBJ']),true);
			//存储下原始数据
			@file_put_contents('sendRealStockInAmount_' . time() . '.txt',var_dump($json,true));

			try{
				foreach($json['porderList'] as $key => $val){
					//更新订单状态
					$time = strtotime($val['callInDate']);
					$sql = "update ra_hangzhou_order set status = '" . HANGZHOU.SUCCESS . "',time = '$time' where code = '$val[code]";
					//更新商品状态
					if(mysql_query($sql)){
						$id = getOne("select id from ra_hangzhou_order where code = '$val[code]'");
						foreach($val['Item'] as $g){
							$sql = "update ra_hangzhou_order_goods set RealInQty = '$g[RealInQty]', damageNum = '$g[damageNum]' where order_id = $id and commodityBarcode = '$g[commodityBarcode]'";
							mysql_query($sql);

							//按照commonid来更新goods表中和goods_common表中的状态以及数量
							$goods_commonid = getOne("select goods_commonid from ra_hangzhou_order_goods where order_id = $id and commodityBarcode = '$g[commodityBarcode]'");
							//防止数据出错
							if(empty($goods_commonid)){
								continue;
							}

							$sql = "update ra_goods set goods_storage = '$g[RealInQty]',goods_verify = 1 where goods_commonid = $goods_commonid";
							mysql_query($sql);
							$sql = "update ra_goods_common set goods_storage = '$g[RealInQty]',goods_verify = 1 where goods_commonid = $goods_commonid";
							mysql_query($sql);

							//更新ra_hangzhou_goods表中的状态
							$sql = "update ra_hangzhou_goods set status = '" . HANGZHOU.SUCCESS . "' where goods_commonid = $goods_commonid";
							mysql_query($sql);



						}
					}
				}

				$result = array(
					'Response' => array(
						'resultCode' => '1000',
						'resultMsg' => '接收成功'
					)
				);
				exit(json_encode($result));


			}
			catch(Exception $e){

				$result = array(
					'Response' => array(
						'resultCode' => '1005',
						'resultMsg' => '接收失败'
					)
				);
				exit(json_encode($result));
			}


			exit;
		}



		if($interface == 'sendShipOrder'){
			$json = json_decode(base64_decode($_POST['JSON_OBJ']),true);
			//存储下原始数据
			@file_put_contents('sendShipOrder_' . time() . '.txt',var_dump($json,true));


		}



		exit;
	}


	/**
	 * 新上架商品备案
	 */
	
	$sql = "select * from ra_goods_common where goods_verify = 10 and goods_commonid not in (select goods_commonid from ra_hangzhou_goods) limit 500";
	$goods = Model()->query($sql);
	$json = array('Commoditys' => array());

	//商品编号
	$id = getOne("select id from ra_hangzhou_goods order by id desc limit 1");
	if(empty($id)){
		$id = 0;
	}

	for($i = 0; $i < 500 && $i < count($goods); $i++){
		$item = $goods[$i];

		$store_info = getRow("select * from ra_store where store_id = $item[store_id]");
		//已经关闭的店铺不能参与！
		if($store_info['store_state'] != 1){
			continue;
		}

		$id++;
		$str = $id;
		for($i = strlen($id); $i < 4; $i++){
			$str = '0' . $str;
		}

		$data = array(
			'goods_extend' => getRow("select * from ra_custom_hangzhou_goods where goods_commonid = " . $item['goods_commonid']),
			'goods_common' => $item
		);

		if($item['brand_id'] > 0){
			$brand_name = getOne("select brand_name from ra_brand where brand_id = " . $goods['brand_id']);
		}
		else{
			$brand_name = '';
		}

		$json['Commoditys'][] = array(
			"commodityCode" => $param['company_code'] . $str,
			"commodityName" => $data['goods']['goods_name'],
			'commoditySpec' => isset($data['goods_extend']['commoditySpec']) ? $data['goods_extend']['commoditySpec'] : '',
			'commodityArtNo' => isset($data['goods_extend']['commodityArtNo']) ? $data['goods_extend']['commodityArtNo'] : '',
			'commodityMadeTime' => isset($data['goods_extend']['commodityMadeTime']) ? $data['goods_extend']['commodityMadeTime'] : '',
			'durabilityPeriod' => isset($data['goods_extend']['durabilityPeriod']) ? $data['goods_extend']['durabilityPeriod'] : '',
			'brandId' => isset($data['goods_common']['brandId']) ? $data['goods_common']['brandId'] : '',
			'brandName' => $brandName,
			'price' => isset($data['goods_common']['goods_costprice']) ? $data['goods_common']['goods_costprice'] : '',
			'marketPrice' => isset($data['goods_common']['goods_marketprice']) ? $data['goods_common']['goods_marketprice'] : '',
			'serialcontrol ' => isset($data['goods_extend']['serialcontrol ']) ? $data['goods_extend']['serialcontrol '] : '',
			'typeId' => isset($data['goods_common']['gc_id']) ? $data['goods_common']['gc_id'] : '',
			'unit' => isset($data['goods_extend']['unit']) ? $data['goods_extend']['unit'] : '',
			'weight' => isset($data['goods_extend']['weight']) ? $data['goods_extend']['weight'] : '',
			'boxSpec' => isset($data['goods_extend']['boxSpec']) ? $data['goods_extend']['boxSpec'] : '',
			'remark' => isset($data['goods_extend']['remark']) ? $data['goods_extend']['remark'] : '',
			'madeAddr' => isset($data['goods_extend']['madeAddr']) ? $data['goods_extend']['madeAddr'] : '',
			'tradeCountryName' => isset($data['goods_extend']['tradeCountryName']) ? $data['goods_extend']['tradeCountryName'] : '',
			'tradeCountryCode ' => isset($data['goods_extend']['tradeCountryCode ']) ? $data['goods_extend']['tradeCountryCode '] : '',
			'HScode' => isset($data['goods_extend']['HScode']) ? $data['goods_extend']['HScode'] : '',

			'goods_commonid' => $data['goods_common']['goods_commonid']
		);
	}

	//将这些数组按照commodityCode分类
	$readyArr = array();
	foreach($json['Commoditys'] as $key => $val){
		$readyArr[$val['commodityCode']] = $val;

		//去除goods_commonid
		unset($val['goods_commonid']);
		$json['Commoditys'][$key] = $val;
	}


	//商品备案测试
	if(count($json['Commoditys'])){
		send_post($send_goods_url,$json,function($result) use (&$readyArr){
			print_r($result);
			//处理失败的地方
			if($result['resultCode'] != 1000){
				foreach($result['ERROR'] as $key => $item){
					$readyArr[$item['code']]['status'] = 'failed';
				}
			}
			// print_r($resutl);

			//将对的部分插入数据库
			foreach($readyArr as $key => $val){
				$sql = array("insert into ra_hangzhou_goods (id,commodityCode,goods_commonid,status) values(");
				$sql[] = 'null,';
				$sql[] = "'$val[commodityCode]'" . ',';
				$sql[] = $val['goods_commonid'] . ',';
				$sql[] = empty($val['status']) ? "'".HANGZHOU.WAITING."'" : "'".HANGZHOU.FAILED."'";
				$sql[] = ')';
				$sql = implode($sql);
				// echo $sql;
				mysql_query($sql);
			}


		});
	}


	/**
	 * 商品采购入库
	 */
	$sql = "select * from ra_hangzhou_goods where status = '0x01'";
	$PorderList = getAll($sql);
	$json = array('PorderList' => array());

	//整理成店铺索引的数组
	$arr = array();
	foreach($PorderList as $key => $val){
		if(!isset($arr[$val['store_id']])){
			$arr[$val['store_id']] = array();
		}
		$arr[$val['store_id']][] = $val;
	}

	$count = 0;
	foreach($arr as $store_id => $g){
		$store_info = getRow("select * from ra_store where store_id = $val[store_id]");
		//已经关闭的店铺不能参与！
		if($store_info['store_state'] != 1){
			continue;
		}
		$item = array(
			'code' => time() . ($count++),
			'companyCode' => $goods['store_id'],
			'supplierCode' => $goods['store_id'],
			'supplierName' => $store_info['store_name'],
			'callInWarehouse' => 'FLHZ01',
			'totalAmount' => '',
			'type' => '',
			'status' => '',
			'Item' => array() 
		);
		$total = 0;
		foreach($g as $val){
			$goods = getRow("select * from  ra_goods_common where goods_commonid = $val[goods_commonid]");
			$extend = getRow("select * from ra_custom_hangzhou_goods where goods_commonid = $val[goods_commonid]");
			$item['Item'][] = array( 
				'commodityName' => $goods['goods_name'],
				'commodityBarcode' => $goods['sharp'],
				'shouldInQty' => $goods['goods_num'],
				'commodityPrice' => $goods['goods_price'],

				'goods_commonid' => $goods['goods_commonid']
			);
			$total += $goods['goods_price'] * $goods['goods_num'];
		}
		$item['totalAmount'] = $total;
		$json['PorderList'][] = $item;
	}

	if(count($json['PorderList'])){
		$backup = $json['PorderList'];
		//去除没用的commonid
		foreach($json['PorderList'] as $key => &$val){
			foreach($val['Item'] as $k => &$v){
				unset($v['goods_commonid']);
			}
		}

		send_post($porder_url,$json,function($result) use ($backup){
			if($result['resultCode'] != 1000){
				return;
			}
			//将这些个订单入库
			foreach($backup['PorderList'] as $key => $val){
				$sql = "insert into ra_hangzhou_order(id,code,time,companyCode,status,totalAmount)
						values(
							null,
							'$val[code]',
							'',
							'$val[companyCode]',
							'0x01',
							'$val[totalAmount]'
						)";

				if(mysql_query($sql)){
					$id = mysql_insert_id();
					foreach($val['Item'] as $g){
						$sql = "insert into ra_hangzhou_order_goods(id,order_id,commodityName,commodityBarcode,shouldInQty,goods_commonid)
							values(
								null,
								$id,
								'$g[commodityName]',
								'$g[commodityBarcode]',
								'$g[shouldInQty],
								'$g[goods_commonid]',
							)";
						mysql_query($sql);
					}
					
				}
			}
		});
	}


	/**
	 * 订单备案
	 */
	$sql = "select * from ra_order where order_sn not in (select order_sn from ra_order)";
	$orders = getAll($sql);
	$json = array('Orders' => array());
	foreach($orders as $key => $order){
		$common = getRow("select * from ra_order_common where order_id = " . $order['order_id']);
		$store_info = getRow("select * from ra_store where store_id = " . $order['store_id']);
		if($store_state['store_state'] != 1){
			continue;
		}

		$receiver_info = unserialize($common['reciver_info']);

		$province = getOne("select area_name from ra_area where area_id = " . $common['reciver_province_id']);
		$city = getOne("select area_name from ra_area where area_id = " . $common['reciver_city_id']);

		$item = array(
			"orderCode" => $param['company_code'] . $order['order_sn'],
			"orderDate" => date('Y-m-d H:i:s'),
			"outCode" => '',
			"expressName" => '',
			"expressNo" => '',
			"receiverName" => $common['reciver_name'],
			"buyernick" => '',
			"mobile" => $order['phone'],
			"warehouseCode" => 'FLHZ01',
			"shopid" => $order['store_id'],
			"shop" => $store_info['store_name'],
			"buyerMessage" => $common['order_message'],
			"remark" => '',
			"systemRemark" => '',
			"telPhone" => '',
			"province" => $province,
			"city" => $city,
			"district" => '',
			"receiverAddress" => $receiver_info['address'],
			"receiverZip" =>'',
			"isCashOnDelivery" => '',
			"payType" => '03',
			"payCompanyCode" => '',
			"payNumber" => '',
			"orderTotalAmount" => '120.00',
			"orderGoodsAmount" => '120.00',
			"orderTaxAmount" => '0',
			"feeAmount" => '0',
			"tradeTime" => date('Y-m-d H:i:s',$order['payment_time']),
			"currCode" => '142',
			"totalAmount" => '120.00',
			"purchaserId" => $order['buyer_id'],
			"id" => $order['buyer_id'],
			"name" => $order['buyer_name'],
			"telNumber" => $order['phone'],
			"paperType" => '01',
			"paperNumber" => $order['idcard'],
			"address" => $receiver_info['address'],
			'OrderDtls' => array()
		);
	}

	


	// echo 123;
	// print_r($json);
	exit;


	function send_post($url,$json,$callback = null){
		global $param;
		$param['JSON_OBJ'] = base64_encode(json_encode($json));
		$param['datetime'] = date("YmdHis");
		$sign = $param['v'] . $param['ip'] . $param['sessionKey'] . $param['datetime'] . $param['appKey'];
		$param['sign'] = strtoupper(md5($sign));
		$result = file_get_contents_post($url,$param);
		echo $result;

		if($callback){
			$result = json_decode($result,true);
			$callback($result['ROWSET']);
		}
	}

	function file_get_contents_post($url, $post) {  
	    $options = array(  
	        'http' => array(  
	            'method' => 'POST',  
	            // 'content' => 'name=caiknife&email=caiknife@gmail.com',  
	            'content' => http_build_query($post),  
	        ),  
	    );  
	  
	    $result = file_get_contents($url, false, stream_context_create($options));  
	  
	    return $result;  
	}  
	//$goods = Model()->table('goods')->where(array('goods_verify' => 10))->select();
	// file_put_contents('lot.txt', 123456),
?>